<template>
  <!--账户转账管理-->
  <div>
    <SectionContainer class="u-p20">
      <SectionTitle>账户转账管理</SectionTitle>

      <!-- 表格 -->
      <TableFull
        :data="tableData"
        :total="tableTotal"
        :current-page="page.pageNo"
        @current-change="currentChange"
        @size-change="sizeChange"
      >
        <el-form
          class="m-filter"
          inline
          slot="handle"
        >
          <el-form-item>
            <el-select
              size="small"
              filterable
              placeholder="请选择账户名称/登录账号"
              v-model="filter.account"
            >
              <el-option
                v-for="(item, index) in accountOptions"
                :key="index"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              size="small"
              filterable
              placeholder="请选择公司名称"
              v-model="filter.company"
            >
              <el-option
                v-for="(item, index) in companyOptions"
                :key="index"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              size="small"
              filterable
              placeholder="请选择账户状态"
              v-model="filter.status"
            >
              <el-option
                :value="0"
                label="全部状态"
              ></el-option>
              <el-option
                :value="2"
                label="启用"
              ></el-option>
              <el-option
                :value="1"
                label="停用"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="small"
              @click="search"
            >查询</el-button>
          </el-form-item>
        </el-form>
        <template slot="column">
          <el-table-column
            :resizable="false"
            align="center"
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-permission="['financial_transfer_recharge']"
                v-if="scope.row.auditMap.internalAudit === '已通过' && scope.row.accountStatus === '启用'"
                effect="dark"
                placement="top"
                content="充值"
              >
                <i
                  @click="openPay(scope.row)"
                  class="u-table-handle iconfont iconfont-18"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['financial_transfer_rollout']"
                v-if="scope.row.amount > 0"
                effect="dark"
                placement="top"
                content="转出"
              >
                <i
                  @click="openPayment(scope.row)"
                  class="u-table-handle iconfont iconfont-19"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            :resizable="false"
            align="center"
            v-for="(item, index) in tableColumn"
            :key="index"
            :prop="item.prop"
            :width="item.width"
            :label="item.label"
          >
            <template slot-scope="scope">
              <!-- 账户属性 -->
              <template v-if="item.prop === 'userType'">{{mapValue(ADVERTISER_PROPERTY, scope.row.userType)}}</template>
              <!-- 其他 -->
              <template v-else>{{scope.row[item.prop]}}</template>
            </template>
          </el-table-column>
        </template>
      </TableFull>
    </SectionContainer>

    <!-- 充值弹窗 -->
    <Dialog
      :visible.sync="payVisible"
      :width="600"
      title="充值"
    >
      <el-form
        label-width="120px"
        class="u-pl20 u-pr20 u-pt20"
        ref="payForm"
        :model="payData"
        :rules="payRules"
      >
        <Tip style="margin-left: 135px">{{principalUnit}}</Tip>
        <!--充值本金-->
        <el-form-item
          label="充值本金："
          prop="principal"
        >
          <el-input
            class="u-w350"
            placeholder="最低0.01元"
            v-model="payData.principal"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!--返点-->
        <el-form-item
          label="返点："
          prop="rebates"
        >
          <el-input
            class="u-w350"
            placeholder="请输入返点"
            v-model="payData.rebates"
          >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <!--账户充值金额 = 充值本金+充值本金*返点-->
        <el-form-item label="账户充值金额：">
          <el-input
            disabled
            class="u-w350"
            placeholder="充值本金+充值本金*返点"
            :value="payAmount"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!--交易类型-->
        <el-form-item label="交易类型：">充值</el-form-item>
        <!--转出方-->
        <el-form-item label="转出方：">管理员账号</el-form-item>
        <!--接收方-->
        <el-form-item label="接收方：">{{updateItem.company}}<span class="c-hint-major">（{{updateItem.loginName}}）</span></el-form-item>
        <!--备注-->
        <el-form-item label="备注：">
          <el-input
            type="textarea"
            autosize
            placeholder="请输入备注"
            v-model="payData.remarks"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row
        class="u-pb20"
        type="flex"
        justify="center"
      >
        <el-button
          type="primary"
          size="small"
          @click="actionPay"
        >立即充值</el-button>
      </el-row>
    </Dialog>

    <!-- 转出弹窗 -->
    <Dialog
      :visible.sync="paymentVisible"
      :width="600"
      title="转出"
    >
      <el-form
        label-width="120px"
        class="u-pl20 u-pr20 u-pt20"
        ref="paymentForm"
        :model="paymentData"
        :rules="paymentRules"
      >
        <!--账户余额-->
        <el-form-item label="账户余额：">
          <span>{{updateItem.adAmount}}元</span>
          <el-button
            v-if="isVisiblePauser"
            @click="pauserAllPlan"
            style="margin: 4px 0 0 10px;"
            type="primary"
            size="small"
          >暂停所有广告</el-button>
          <div
            v-if="isVisiblePauser"
            class="c-hint-warn"
          >温馨提示：暂停所有广告的24小时之后才可进行资金转出</div>
          <div
            v-if="isVisiblePauserTimeout"
            class="c-hint-warn"
          >温馨提示：{{paymentTimeout}}之后才可进行资金转出</div>
        </el-form-item>
        <!--转账金额-->
        <el-form-item
          label="转账金额："
          prop="amount"
          v-show="isVisiblePayment"
        >
          <el-input
            class="u-w350"
            placeholder="转账金额不大于当前余额，且不能少于0"
            v-model="paymentData.amount"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!--交易类型-->
        <el-form-item label="交易类型：">转出</el-form-item>
        <!--转出方-->
        <el-form-item label="转出方：">{{updateItem.company}}<span class="c-hint-major">（{{updateItem.loginName}}）</span></el-form-item>
        <!--接收方-->
        <el-form-item label="接收方：">管理员账号</el-form-item>
        <!--备注-->
        <el-form-item
          label="备注："
          v-if="isVisiblePayment"
        >
          <el-input
            type="textarea"
            autosize
            placeholder="请输入备注"
            v-model="paymentData.remarks"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row
        class="u-pb20"
        type="flex"
        justify="center"
      >
        <el-button
          v-if="isVisiblePayment"
          type="primary"
          size="small"
          @click="actionPayment"
        >立即转出</el-button>
      </el-row>
    </Dialog>
  </div>
</template>

<script>
import SectionContainer from "@/components/section-container";
import SectionTitle from "@/components/section-title";
import Dialog from "@/components/dialog";
import TableFull from "@/components/table-full";
import Tip from "@/components/tip";

import { ADVERTISER_PROPERTY } from "@/assets/js/common-option";
import { splitAccount, mapValue } from "@/utils";
import { decimalMultiply, decimalDivision } from "@/utils/decimal";
import permissionMixin from "@/mixins/permission";
import {
  fetchFinancialSelect,
  fetchFinancialTransferList,
  fetchFinancialTransferPay,
  fetchFinancialTransferPayment,
  fetchFinancialTransferPaymentDetail,
  fetchFinancialTransferPauser
} from "@/api";

export default {
  mixins: [permissionMixin],
  components: {
    Dialog,
    SectionContainer,
    SectionTitle,
    TableFull,
    Tip
  },
  data() {
    return {
      ADVERTISER_PROPERTY,

      // 充值、转账
      payVisible: false,
      paymentVisible: false,
      updateItem: {},

      // 下拉选项
      accountOptions: [],
      companyOptions: [],

      // 筛选
      filter: {
        account: "全部账户",
        company: "全部公司",
        status: 2
      },

      page: {
        pageNo: 1,
        pageSize: 50
      },

      // 表格
      tableColumn: [
        {
          label: "账户名称",
          prop: "userName",
          width: 150
        },
        {
          label: "登录账号",
          prop: "loginName"
        },
        {
          label: "公司名称",
          prop: "company"
        },
        {
          label: "账户属性",
          prop: "userType",
          width: 120
        },
        {
          label: "账户余额（元）",
          prop: "amount",
          width: 150
        },
        {
          label: "账户状态",
          prop: "accountStatus"
        }
      ],
      tableData: [],
      tableTotal: 0,

      // 充值
      payData: {
        principal: "",
        rebates: "",
        remarks: ""
      },
      payRules: {
        principal: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === "" || value < 0.01 || isNaN(value)) {
              callback(new Error("充值本金最低为0.01元"));
            } else if (value > 100000000) {
              callback(new Error("充值本金最高1亿元"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("请最多保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        },
        rebates: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === "" || value < 0 || isNaN(value)) {
              callback(new Error("返点最低为0"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("请最多保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      },
      // 转出
      paymentData: {
        amount: "",
        remarks: ""
      },
      paymentRules: {
        amount: {
          required: true,
          validator: (rule, value, callback) => {
            if (
              value === "" ||
              isNaN(value) ||
              value <= 0 ||
              value > this.updateItem.adAmount
            ) {
              callback(new Error("转账金额不可大于当前余额，且不能少于0元"));
            } else if (
              String(value).length > String(Number(value).toFixed(5)).length
            ) {
              callback(new Error("请最多保留5位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      }
    };
  },
  computed: {
    // 充值本金单位提示
    principalUnit() {
      if (this.payData.principal > 99999999) {
        return "亿";
      } else if (this.payData.principal > 9999999) {
        return "千万";
      } else if (this.payData.principal > 999999) {
        return "百万";
      } else if (this.payData.principal > 99999) {
        return "十万";
      } else if (this.payData.principal > 9999) {
        return "万";
      } else if (this.payData.principal > 999) {
        return "千";
      } else if (this.payData.principal > 99) {
        return "百";
      } else if (this.payData.principal > 9) {
        return "十";
      } else {
        return "";
      }
    },
    // 账户充值金额 = 充值本金+充值本金*返点
    payAmount() {
      if (this.payData.principal > 0 && this.payData.rebates >= 0) {
        return decimalMultiply(
          this.payData.principal,
          1 + decimalDivision(this.payData.rebates, 100)
        );
      }
      return "";
    },
    // 暂停距离24小时还剩余多久
    paymentTimeout() {
      let minute = (24 * 60 * 60 * 1000 - this.updateItem.StopTime) / 1000 / 60;
      let h = Math.floor(minute / 60);
      let m = Math.ceil(minute - h * 60);
      if (h > 0) {
        return `${h}小时${m}分`;
      }
      return `${m}分`;
    },
    // 是否显示暂停所有计划按钮
    isVisiblePauser() {
      return !this.updateItem.OpenPlan;
    },
    // 是否显示暂停倒计时
    isVisiblePauserTimeout() {
      let time = 24 * 60 * 60 * 1000;
      return (
        this.updateItem.OpenPlan &&
        this.updateItem.StopTime > 0 &&
        this.updateItem.StopTime < time
      );
    },
    // 是否显示立即转账按钮
    isVisiblePayment() {
      return (
        this.updateItem.OpenPlan &&
        this.updateItem.StopTime > 24 * 60 * 60 * 1000
      );
    }
  },
  methods: {
    mapValue,

    // 充值弹窗
    openPay({ company, loginName, userId }) {
      this.payVisible = true;
      this.updateItem = {
        company,
        loginName,
        userId
      };
    },
    // 充值
    actionPay() {
      this.$refs["payForm"].validate(valid => {
        if (valid) {
          fetchFinancialTransferPay({
            query: {
              userId: this.updateItem.userId,
              transaction: 1,
              principal: this.payData.principal,
              rebates: this.payData.rebates,
              remarks: this.payData.remarks
            }
          }).then(() => {
            this.$message({
              message: "操作成功",
              duration: 1000
            });
            this.payVisible = false;
            this.getTable();
          });
        }
      });
    },
    // 暂停所有广告
    pauserAllPlan() {
      fetchFinancialTransferPauser({
        query: {
          userId: this.updateItem.userId
        }
      }).then(() => {
        this.paymentVisible = false;
        this.$message({
          message: "暂停所有计划成功",
          duration: 1000
        });
      });
    },
    // 转出弹窗
    openPayment({ company, loginName, userId }) {
      this.paymentVisible = true;
      this.fetchFinancialTransferPaymentDetail(userId).then(data => {
        this.updateItem = {
          ...data,
          company,
          loginName,
          userId
        };
      });
    },
    // 转出
    actionPayment() {
      this.$refs["paymentForm"].validate(valid => {
        if (valid) {
          fetchFinancialTransferPayment({
            query: {
              userId: this.updateItem.userId,
              transaction: 2,
              amount: this.paymentData.amount,
              remarks: this.paymentData.remarks
            }
          }).then(() => {
            this.$message({
              message: "操作成功",
              duration: 1000
            });
            this.paymentVisible = false;
            this.getTable();
          });
        }
      });
    },
    // 获取转出信息
    fetchFinancialTransferPaymentDetail(userId) {
      return fetchFinancialTransferPaymentDetail({
        query: {
          userId
        }
      }).then(res => {
        return res.data;
      });
    },
    // 下拉：账号、名称、公司
    fetchFinancialSelect() {
      fetchFinancialSelect().then(res => {
        this.accountOptions = [
          {
            name: "全部账户"
          }
        ].concat(res.data.account);
        this.companyOptions = [
          {
            name: "全部公司"
          }
        ].concat(res.data.company);
      });
    },
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 获取表格数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      fetchFinancialTransferList({
        query: {
          ...this.page,
          status: this.filter.status,
          account:
            this.filter.account === "全部账户"
              ? ""
              : splitAccount(this.filter.account).email,
          company: this.filter.company === "全部公司" ? "" : this.filter.company
        }
      }).then(res => {
        this.tableData = res.data.list || [];
        this.tableTotal = res.data.count;
      });
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    }
  },
  created() {
    this.fetchFinancialSelect();
    this.getTable();
  }
};
</script>